<template>
    <div class="components-myupload">
        <ul class="el-upload-list el-upload-list--picture-card" v-if="isShowList && listType == 'picture-card' && file_list.length > 0">
            <li v-for="(item,index) in file_list" :key="index" tabindex="0" class="el-upload-list__item is-ready">
                <div>
                    <video width="120" height="120" controls v-if="fileMedia == 'video'"  class="el-upload-list__item-thumbnail">
                        <source :src="getUrl(item.url)" type="video/mp4">
                    </video>
                    <img v-else :src="getUrl(item.url)" alt="" class="el-upload-list__item-thumbnail">
                    <!-- <img :src="getUrl(item)" alt="" class="el-upload-list__item-thumbnail">  -->
                    <span class="el-upload-list__item-actions">
                        <span class="el-upload-list__item-preview" @click="handlePictureCardPreview(item)"><i class="el-icon-zoom-in"></i></span> 
                        <span class="el-upload-list__item-delete" @click="uploadRemove(index)"><i class="el-icon-delete"></i></span>
                    </span>
                </div>
            </li>
        </ul>
        <el-upload
            :class="'upload-'+listType"
            ref="uploadFile"
            :action="uploadFileUrl"
            :headers="headers"
            :list-type="listType"      
            :limit="limit"
            :multiple="limit>1 ? true : false"
            :accept="acceptType"
            :on-error="uploadError"
            :on-progress="uploadProgress"
            :before-upload="handleBeforeUpload"
            :on-success="uploadSuccess"
            :show-file-list="false"
            :data="params"
            :name="fileName">
            <!-- :on-exceed="handleExceed" -->
            <i v-if="listType == 'picture-card'" class="el-icon-plus" v-loading="loading"></i>
            <el-button v-else size="small" icon="el-icon-upload2" type="primary" plain :loading="loading">点击上传</el-button>     
        </el-upload>
        <div class="el-upload__tip" slot="tip" v-if="showTip">
            请上传
            <template v-if="fileSize"> 大小不超过 <b style="color: #f56c6c">{{ fileSize }}MB</b> </template>
            <template v-if="fileType"> 格式为 <b style="color: #f56c6c">{{ fileType.join("/") }}</b> </template>
            的文件
        </div>
        <ul class="el-upload-list el-upload-list--text" v-if="isShowList && listType == 'text' && file_list.length > 0">
            <li tabindex="0" class="el-upload-list__item is-success"  v-for="(item,index) in file_list" :key="index">
                <a class="el-upload-list__item-name">
                    <i class="el-icon-document"></i>{{item.name}}
                </a>
                <label class="el-upload-list__item-status-label">
                    <i class="el-icon-upload-success el-icon-circle-check"></i>
                </label>
                <i class="el-icon-close" @click="uploadRemove(index)"></i>
                <i class="el-icon-close-tip">按 delete 键可删除</i>
            </li>
        </ul>
    <el-dialog :visible.sync="dlg_view.is_show" append-to-body>
        <div class="align-center">
            <video width="200" height="200" controls v-if="fileMedia == 'video'">
                <source :src="getUrl(dlg_view.url)" type="video/mp4">
            </video>
            <img v-else style="max-width:100%" :src="getUrl(dlg_view.url)" alt="">
        </div>
    </el-dialog>
    </div>    
</template>
<script>
import { baseUrl } from '@/config/env'
import {getStore, setStore} from '@/util/store'
export default {
    props:{
        value: {
            type: String,
        },
        listType:{
            type: String,
            default: () => 'text'
        },
        fileMedia: { // 上传文件的类型，主要是区分视频和图片
            type: String,
        },
        fileSize: {
            type: Number,
            default: 100,
        },
        fileType: {
            type: Array,
            default: () => ["png", "jpg", "jpeg","doc", "docx", "xls", "xlsx", "ppt", "txt", "pdf", "rar", "zip", "7z"],
        },
        fileName:{
            type: String,
            default: () => 'file'
        },
        isShowTip: {
            type: Boolean,
            default: true
        },
        isShowList:{
            type: Boolean,
            default: true
        },
        params:{
            type: Object,
            // default: () => { return {resType: "file"} }
        },
        limit:{
            type: Number,
            default: () => 1
        },
        api: {
            type: String,
            default: () => '/admin/sys-file/upload',//"/eduoss/fileoss"
        }

    },
    data(){
        return{
            loading: false,
            // uploadFileUrl: process.env.VUE_APP_BASE_API + this.api, 
            uploadFileUrl: this.api, 
            headers: { Authorization: "Bearer " + this.$store.getters.access_token, 'TENANT-ID': 1, }, //getStore({name: 'tenantId'})
            file_list:[],
            file: null,
            dlg_view:{
                is_show: false,
                url: null,
            },
        }
    },
    created() {
        this.file_list = this.list;
    },
    // watch: {
    //     value(newVal, oldVal){
    //         this.file_list = this.list;
    //         console.log(this.file_list);
    //     }
    // },
    computed: {
        acceptType(){
            let arr = this.fileType.map(item => '.'+item);
            return arr.join(',');
        },
        // 是否显示提示
        showTip() {
            return this.isShowTip && (this.fileType || this.fileSize);
        },
        // 列表
        list() {
            if (this.value) {
                // 首先将值转为数组
                let list;
                if(Array.isArray(this.value) ){
                    list = this.value;
                }else{
                    list = this.value.split(',');
                }
                // 然后将数组转为对象数组
                return list.map((item) => {
                    if (typeof item === "string") {
                        item = { name: item, url: item };
                    }
                    return item;
                });
            } else {
                this.file_list = [];
                return [];
            }
        },
    },
    methods:{
        // 上传前校检格式和大小
        handleBeforeUpload(file) {
            this.file = file;
            // 校检文件类型
            if (this.fileType) {
                let fileExtension = "";
                if (file.name.lastIndexOf(".") > -1) {
                fileExtension = file.name.slice(file.name.lastIndexOf(".") + 1);
                }
                const isTypeOk = this.fileType.some((type) => {
                if (file.type.indexOf(type) > -1) return true;
                if (fileExtension && fileExtension.indexOf(type) > -1) return true;
                return false;
                });
                if (!isTypeOk) {
                this.$message.error(`文件格式不正确, 请上传${this.fileType.join("/")}格式文件!`);
                return false;
                }
            }
            // 校检文件大小
            if (this.fileSize) {
                const isLt = file.size / 1024 / 1024 < this.fileSize;
                if (!isLt) {
                this.$message.error(`上传文件大小不能超过 ${this.fileSize} MB!`);
                return false;
                }
            }
            return true;
        },
        handleExceed(files, fileList) {
            this.$message.error(`上传的文件已超过` + this.limit + '个');
        },
        uploadProgress(event,file, fileList){
            this.loading = true;
        },
        uploadSuccess(res, file, fileList) {
            this.loading = false;
            if(res.hasOwnProperty('code')){
                if (res.code == 0) {
                    if(this.limit > 1){
                        if(this.file_list.length < this.limit){
                            this.file_list.push({name: file.name , url: res.data.url, local_url: baseUrl + res.data.url, res: res.data});
                        }else{
                            this.$message.error(`上传的文件已超过` + this.limit + '个');
                        }
                    }
                    if(this.limit == 1){
                        this.file_list = [{name: file.name , url: res.data.url, local_url: baseUrl + res.data.url, res: res.data}]
                    }
                    let url = this.file_list.map(item => item.url);
                    this.$emit('update:value', url.join(','))
                    this.$emit('success', this.file_list);
                } else {
                    this.$message.error(res.msg)
                }
            }else{
                this.$emit('success', res);
            }
            if(this.limit == 1){
                this.$refs.uploadFile.clearFiles();
            }
        },
        uploadRemove(index) {
            this.file_list.splice(index, 1);
            this.$forceUpdate();
            let url = this.file_list.map(item => item.url);
            this.$emit('update:value', url.join(','));
            this.$emit('success', this.file_list);
        },
        uploadError(err) {
            this.$message.error('上传失败，请重试')
        },
        // 预览
        handlePictureCardPreview(file) {
            this.dlg_view.url = file.url;
            this.dlg_view.is_show = true;
        },
        // 如果上传成功返回的url不是可访问的地址，则加上域名
        getUrl(url){
            if(url){
                if(url.indexOf('http') == -1){
                    return baseUrl + url;
                }
            }
            return url;
        }
        
    }
}
</script>
<style lang="scss" scoped>
.components-myupload{
  .upload{
    &-picture-card{
      display:inline-block;
      ::v-deep .el-upload--picture-card{
          width:128px;height:128px;line-height:126px;
      }
      
    }
  }
  .el-upload-list--picture-card{
       display:inline-block;
       .el-upload-list__item{
          width:128px;height:128px;
       }
    }
}
</style>